import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { MaintenanceServiceProxy, MaintenanceEditDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import { CalendarModule } from 'primeng/primeng';

import * as _ from 'lodash';
import * as moment from 'moment';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditMaintenanceModal',
    templateUrl: './create-or-edit-maintenance-modal.component.html'
})
export class CreateOrEditMaintenanceModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('dateStartPicker') dateStartPicker: ElementRef;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    es: any;
    maintenance: MaintenanceEditDto = new MaintenanceEditDto();
    beginDate: Date;
    endDate: Date;

    constructor(
        injector: Injector,
        private _maintenanceService: MaintenanceServiceProxy
    ) {
        super(injector);
    }
    ngOnInit() {
        this.es = {
            firstDayOfWeek: 1,
            dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            today: 'Hoy',
            clear: 'Borrar',

            dayNames: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"],
            dayNamesShort: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],


            monthNamesShort: ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"],

        };
    }

    show(id?: number): void {
        this.active = true;
        this._maintenanceService.getEquipMaintenanceForEdit(id).subscribe(result => {
            this.maintenance = result;
            this.beginDate = this.maintenance.dateStart.year() === 1 ? undefined : this.maintenance.dateStart.toDate();
            this.endDate = this.maintenance.dateEnd.year() === 1 ? undefined : this.maintenance.dateEnd.toDate();
            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;
        this.maintenance.dateStart = moment(this.beginDate).add(8, 'hour');
        this.maintenance.dateEnd = moment(this.endDate).add(8, 'hour');

        this._maintenanceService.createOrUpdateEquipMaintenance(this.maintenance)
            .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
